package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"path"
)

func NotFound(w http.ResponseWriter, r *http.Request) {
	bs, _ := os.ReadFile("index.html")

	fmt.Fprintf(w, "%s", string(bs))
}

func FileServerWithCustom404(fs http.FileSystem) http.Handler {
	fsh := http.FileServer(fs)
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, err := fs.Open(path.Clean(r.URL.Path))
		if os.IsNotExist(err) {
			NotFound(w, r)
			return
		}
		fsh.ServeHTTP(w, r)
	})
}

func main() {
	file, _ := os.Getwd()

	port := flag.String("port", ":80", "http listen port")
	path := flag.String("path", file, "http listen port")
	//获取系统当前路径
	flag.Parse()

	//fs := http.FileServer(http.Dir(file))

	//http.Handle("/", fs)
	http.Handle("/", FileServerWithCustom404(http.Dir(file)))
	//http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	//	if r.URL.Path != "/" {
	//		w.WriteHeader(404)
	//		w.Write([]byte("<h1>404</h1>"))
	//	} else {
	//		w.Write([]byte("index"))
	//	}
	//})

	fmt.Printf("Listening[%s] at 0.0.0.0%s.\n", *path, *port)
	// 启动web服务
	//h := http.FileServer(http.Dir(*path))
	//err := http.ListenAndServe(*port,h)
	err := http.ListenAndServe(*port, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
